package com.yingyi.async;


import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

import java.nio.charset.StandardCharsets;

/**
 * 异步消息通常用在对响应时间敏感的业务场景，即发送端不能容忍长时间地等待Broker的响应。
 */
public class Producer {
    public static void main(String[] args) throws Exception {
        // 创建生产者对象
        DefaultMQProducer producer = new DefaultMQProducer("async_producer_group");
        // 设置NameSvr地址
        producer.setNamesrvAddr("localhost:9876");

        // 启动
        producer.start();
        // 创建消息 Topic tag body
        Message message = new Message("async", "hello", "nothing is possible".getBytes(StandardCharsets.UTF_8));
        // SendCallback接收异步返回结果的回调
        producer.send(message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("success: " + sendResult.getMsgId());
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println("exception:" + throwable.getMessage());
            }

        });

        //关闭
        //producer.shutdown();
    }
}
